import json
import time
from random import random
from time import sleep

import ddddocr
import requests
from DrissionPage import ChromiumPage


# 获取华为任务数据
def get_huawei_adgroup_headers():
    # 初始化浏览器
    page = ChromiumPage()
    #启动网络监听（在访问页面前）
    page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')  # 监听包含该域名的所有请求
    try:
        # 访问登录页面
        page.get('https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a1be0000001d17494785911728219%26h%3D1749478591.1740%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc9def02898aeee1f74803c1a5c49b37c9f6e13b813685ecb95b831b34f3a6302&validated=true')
        # 输入账号密码（替换为你的测试账号）
        page.ele('.hwid-input userAccount').input('business_m@igame58.com')
        page.ele('.hwid-input hwid-input-pwd').input('LEYOU123')  # 实际使用时建议从环境变量读取
        # 点击登录按钮（根据实际页面调整选择器）
        login_btn = page.ele('.normalBtn', timeout=10)
        login_btn.click()
        sleep(5)  # 等待登录完成

        # 获取最新请求的请求头
        latest_request = page.listen.wait()

        headers = latest_request.request.extra_info.headers
        # 任务列表接口
        url = "https://svc-drcn.ads.huawei.com/ppsdspportal/v1/adgroups/query"
        # 请求体数据
        payload = {
            "pageNum": 1,
            "pageSize": 100,
            "orderBy": "",
            "orderType": "",
            "startTime": "2025-01-01",
            "endTime": "2025-06-09",
            "campaignType": None,
            "timeLine": "STAT_REPORTING_TIME",
            "promotionType": 2,
            "campaignIds": [],
            "adgroupNameOrId": "",
            "productAppId": "",
            "creativeSizeId": "",
            "filterNoStat": 0,
            "serviceProviderIds": [],
            "flowResourceList": None,
            "marketingGoalList": None,
            "status": None,
            "productTypeList": None,
            "priceTypeList": None,
            "ocpxStatus": None,
            "deepOptimizeType": None,
            "changeToOcpcStatus": None,
            "ocpcStrategy": None,
            "objectiveTypeList": None,
            "simpleMode": None
        }
        try:
            # 发送POST请求
            response = requests.post(
                url,
                headers=headers,
                json=payload  # 使用json参数自动序列化为JSON并设置Content-Type
            )
            # 检查响应状态
            if response.status_code == 200:
                print("响应数据:", response.text)  # 获取JSON格式响应
                return response.text
            else:
                print(f"请求失败，状态码: {response.status_code}")
                print("响应内容:", response.text)
        except requests.exceptions.RequestException as e:
            print(f"请求发生异常: {e}")
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")


    finally:
        page.quit()  # 确保关闭浏览器

# 656获取华为任务分页数据汇总
def get_huawei_adgroup_page656():
    # 初始化浏览器
    page = ChromiumPage()
    # 启动网络监听
    page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')
    try:
        # 访问登录页面
        page.get(
            'https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a1be0000001d17494785911728219%26h%3D1749478591.1740%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc9def02898aeee1f74803c1a5c49b37c9f6e13b813685ecb95b831b34f3a6302&validated=true')

        # 输入账号密码
        page.ele('.hwid-input userAccount').input('business_m@igame58.com')
        page.ele('.hwid-input hwid-input-pwd').input('LEYOU123')

        # 点击登录按钮
        login_btn = page.ele('.normalBtn', timeout=10)
        login_btn.click()
        sleep(2)  # 等待登录完成

        # 滑块验证重试逻辑
        for retry in range(3):
            print(f"尝试滑块验证 (第 {retry + 1} 次)...")
            success, headers = slide_test(page)
            if success:
                print("滑块验证成功")
                break
            else:
                print(f"滑块验证失败，等待1秒后重试...")
                sleep(1)
        else:
            print(f"滑块验证失败，已达最大重试次数 {3} 次")

        # 初始化分页参数
        page_num = 1
        page_size = 100
        all_data = []
        has_more = True

        # 分页查询循环
        while has_more:
            # 请求体数据
            payload = {
                "pageNum": page_num,
                "pageSize": page_size,
                "orderBy": "",
                "orderType": "",
                "startTime": "2025-01-01",
                "endTime": "2025-06-15",
                "campaignType": None,
                "timeLine": "STAT_REPORTING_TIME",
                "promotionType": 2,
                "campaignIds": [],
                "adgroupNameOrId": "",
                "productAppId": "",
                "creativeSizeId": "",
                "filterNoStat": 0,
                "serviceProviderIds": [],
                "flowResourceList": None,
                "marketingGoalList": None,
                "status": None,
                "productTypeList": None,
                "priceTypeList": None,
                "ocpxStatus": None,
                "deepOptimizeType": None,
                "changeToOcpcStatus": None,
                "ocpcStrategy": None,
                "objectiveTypeList": None,
                "simpleMode": None
            }
            try:
                # 发送POST请求
                response = requests.post(
                    "https://svc-drcn.ads.huawei.com/ppsdspportal/v1/adgroups/query",
                    headers=headers,
                    json=payload
                )
                # 检查响应状态
                if response.status_code == 200:
                    data = response.json()
                    # 检查是否有数据
                    if 'data' in data and 'adgroupStatistics' in data['data']:
                        current_page_data = data['data']['adgroupStatistics']
                        all_data.extend(current_page_data)

                        # 检查是否还有更多数据
                        if len(current_page_data) < page_size:
                            has_more = False
                        else:
                            page_num += 1
                    else:
                        print("响应数据格式不符合预期")
                        has_more = False
                else:
                    print(f"请求失败，状态码: {response.status_code}")
                    print("响应内容:", response.text)
                    has_more = False
            except requests.exceptions.RequestException as e:
                print(f"请求发生异常: {e}")
                has_more = False
            except ValueError as e:
                print(f"JSON解析错误: {e}")
                has_more = False
            # 添加适当的延迟，避免请求过于频繁
            sleep(2)
        # data168 = get_huawei_adgroup_page168()
        # all_data.extend(data168)
        print(f"656账户总共获取到 {len(all_data)} 条广告组数据")
        return all_data

    finally:
        page.quit()  # 确保关闭浏览器

# 168获取华为任务分页数据汇总
def get_huawei_adgroup_page168():
    # 初始化浏览器
    page = ChromiumPage()
    # 启动网络监听
    page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')
    try:
        # 访问登录页面
        page.get('https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a4bf7000001d17496045915977400%26h%3D1749604591.5980%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc1721fefb9cebd72e7ff228bf7bad87911c5c8b17c32cc022980dc744bb3eb1f&validated=true')
        # 输入账号密码
        page.ele('.hwid-input userAccount').input('13715176464')
        page.ele('.hwid-input hwid-input-pwd').input('LEYOU123')

        # 点击登录按钮
        login_btn = page.ele('.normalBtn', timeout=10)
        login_btn.click()
        sleep(2)  # 等待登录完成

        # 滑块验证重试逻辑
        for retry in range(3):
            print(f"尝试滑块验证 (第 {retry + 1} 次)...")
            success, headers = slide_test(page)
            if success:
                print("滑块验证成功")
                break
            else:
                print(f"滑块验证失败，等待1秒后重试...")
                sleep(1)
        else:
            print(f"滑块验证失败，已达最大重试次数 {3} 次")

        # 初始化分页参数
        page_num = 1
        page_size = 100
        all_data = []
        has_more = True

        # 分页查询循环
        while has_more:
            # 请求体数据
            payload = {
                "pageNum": page_num,
                "pageSize": page_size,
                "orderBy": "",
                "orderType": "",
                "startTime": "2025-01-01",
                "endTime": "2025-06-15",
                "campaignType": None,
                "timeLine": "STAT_REPORTING_TIME",
                "promotionType": 2,
                "campaignIds": [],
                "adgroupNameOrId": "",
                "productAppId": "",
                "creativeSizeId": "",
                "filterNoStat": 0,
                "serviceProviderIds": [],
                "flowResourceList": None,
                "marketingGoalList": None,
                "status": None,
                "productTypeList": None,
                "priceTypeList": None,
                "ocpxStatus": None,
                "deepOptimizeType": None,
                "changeToOcpcStatus": None,
                "ocpcStrategy": None,
                "objectiveTypeList": None,
                "simpleMode": None
            }
            try:
                # 发送POST请求
                response = requests.post(
                    "https://svc-drcn.ads.huawei.com/ppsdspportal/v1/adgroups/query",
                    headers=headers,
                    json=payload
                )
                # 检查响应状态
                if response.status_code == 200:
                    data = response.json()
                    # 检查是否有数据
                    if 'data' in data and 'adgroupStatistics' in data['data']:
                        current_page_data = data['data']['adgroupStatistics']
                        all_data.extend(current_page_data)

                        # 检查是否还有更多数据
                        if len(current_page_data) < page_size:
                            has_more = False
                        else:
                            page_num += 1
                    else:
                        print("响应数据格式不符合预期")
                        has_more = False
                else:
                    print(f"请求失败，状态码: {response.status_code}")
                    print("响应内容:", response.text)
                    has_more = False
            except requests.exceptions.RequestException as e:
                print(f"请求发生异常: {e}")
                has_more = False
            except ValueError as e:
                print(f"JSON解析错误: {e}")
                has_more = False
            # 添加适当的延迟，避免请求过于频繁
            sleep(1)
        print(f"168账户总共获取到 {len(all_data)} 条广告组数据")
        return all_data

    finally:
        page.quit()  # 确保关闭浏览器


#获取华为计划分页数据汇总
def get_huawei_campaign_page():
    # 初始化浏览器
    page = ChromiumPage()
    # 启动网络监听
    page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')
    try:
        # 访问登录页面
        page.get('https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a1be0000001d17494785911728219%26h%3D1749478591.1740%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc9def02898aeee1f74803c1a5c49b37c9f6e13b813685ecb95b831b34f3a6302&validated=true')

        # 输入账号密码
        page.ele('.hwid-input userAccount').input('business_m@igame58.com')
        page.ele('.hwid-input hwid-input-pwd').input('LEYOU123')

        # 点击登录按钮
        login_btn = page.ele('.normalBtn', timeout=10)
        login_btn.click()
        sleep(5)  # 等待登录完成

        # 获取最新请求的请求头
        latest_request = page.listen.wait()
        headers = latest_request.request.extra_info.headers

        # 初始化分页参数
        page_num = 1
        page_size = 100
        all_data = []
        has_more = True

        # 分页查询循环
        while has_more:
            # 请求体数据
            payload = {
                "pageNum": page_num,
                "pageSize": page_size,
                "status": None,
                "filterNoStat": 0,
                "campaignNameOrId": "",
                "orderBy": "",
                "orderType": "",
                "campaignType": None,
                "flowResourceList": None,
                "marketingGoalList": None,
                "startTime": "2025-01-01",
                "endTime": "2025-06-11",
                "timeLine": "STAT_REQUEST_TIME",
                "promotionType": 2
            }
            try:
                # 发送POST请求
                response = requests.post(
                    "https://svc-drcn.ads.huawei.com/ppsdspportal/v1/campaigns/query",
                    headers=headers,
                    json=payload
                )
                # 检查响应状态
                if response.status_code == 200:
                    data = response.json()
                    # 检查是否有数据
                    if 'data' in data and 'campaignStatistics' in data['data']:
                        current_page_data = data['data']['campaignStatistics']
                        all_data.extend(current_page_data)

                        # 检查是否还有更多数据
                        if len(current_page_data) < page_size:
                            has_more = False
                        else:
                            page_num += 1
                    else:
                        print("响应数据格式不符合预期")
                        has_more = False
                else:
                    print(f"请求失败，状态码: {response.status_code}")
                    print("响应内容:", response.text)
                    has_more = False
            except requests.exceptions.RequestException as e:
                print(f"请求发生异常: {e}")
                has_more = False
            except ValueError as e:
                print(f"JSON解析错误: {e}")
                has_more = False
            # 添加适当的延迟，避免请求过于频繁
            sleep(1)
        data168 = get_huawei_campaign_page168()
        all_data.extend(data168)
        print(f"656总共获取到 {len(all_data)} 条计划数据")
        return all_data

    finally:
        page.quit()  # 确保关闭浏览器

#168获取华为计划
def get_huawei_campaign_page168():
    # 初始化浏览器
    page = ChromiumPage()
    # 启动网络监听
    page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')
    try:
        # 访问登录页面
        page.get('https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a1be0000001d17494785911728219%26h%3D1749478591.1740%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc9def02898aeee1f74803c1a5c49b37c9f6e13b813685ecb95b831b34f3a6302&validated=true')

        # 输入账号密码
        page.ele('.hwid-input userAccount').input('15012800919')
        page.ele('.hwid-input hwid-input-pwd').input('LEYOU123')

        # 点击登录按钮
        login_btn = page.ele('.normalBtn', timeout=10)
        login_btn.click()
        sleep(5)  # 等待登录完成

        # 获取最新请求的请求头
        latest_request = page.listen.wait()
        headers = latest_request.request.extra_info.headers

        # 初始化分页参数
        page_num = 1
        page_size = 100
        all_data = []
        has_more = True

        # 分页查询循环
        while has_more:
            # 请求体数据
            payload = {
                "pageNum": page_num,
                "pageSize": page_size,
                "status": None,
                "filterNoStat": 0,
                "campaignNameOrId": "",
                "orderBy": "",
                "orderType": "",
                "campaignType": None,
                "flowResourceList": None,
                "marketingGoalList": None,
                "startTime": "2025-01-01",
                "endTime": "2025-06-11",
                "timeLine": "STAT_REQUEST_TIME",
                "promotionType": 2
            }
            try:
                # 发送POST请求
                response = requests.post(
                    "https://svc-drcn.ads.huawei.com/ppsdspportal/v1/campaigns/query",
                    headers=headers,
                    json=payload
                )
                # 检查响应状态
                if response.status_code == 200:
                    data = response.json()
                    # 检查是否有数据
                    if 'data' in data and 'campaignStatistics' in data['data']:
                        current_page_data = data['data']['campaignStatistics']
                        # for item in current_page_data:
                        #     campaignId = item['campaignId']
                        #     if str(campaignId) == '37086011':
                        #         print(item)
                        all_data.extend(current_page_data)

                        # 检查是否还有更多数据
                        if len(current_page_data) < page_size:
                            has_more = False
                        else:
                            page_num += 1
                    else:
                        print("响应数据格式不符合预期")
                        has_more = False
                else:
                    print(f"请求失败，状态码: {response.status_code}")
                    print("响应内容:", response.text)
                    has_more = False
            except requests.exceptions.RequestException as e:
                print(f"请求发生异常: {e}")
                has_more = False
            except ValueError as e:
                print(f"JSON解析错误: {e}")
                has_more = False
            # 添加适当的延迟，避免请求过于频繁
            sleep(1)
        print(f"168总共获取到 {len(all_data)} 条计划数据")
        return all_data

    finally:
        page.quit()  # 确保关闭浏览器

def dddd_test():
    # 初始化浏览器
    page = ChromiumPage()
    # 启动网络监听
    page.listen.start('svc-drcn.ads.huawei.com/ppsdspportal/v1/account/balance/query')
    try:
        # 访问登录页面
        page.get(
            'https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?reqClientType=90&loginChannel=90000300&regionCode=cn&loginUrl=https%3A%2F%2Fid1.cloud.huawei.com%3A443%2FCAS%2Fportal%2FloginAuth.html&lang=zh-cn&themeName=red&clientID=101476933&state=null&service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2FloginCallback%3Faccess_type%3Doffline%26client_id%3D101476933%26display%3Dpage%26flowID%3D0a8a4bf7000001d17496045915977400%26h%3D1749604591.5980%26lang%3Dzh-cn%26redirect_uri%3Dhttps%253A%252F%252Fads.huawei.com%252Fusermgtportal%252Fhtml%252Flogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccountlist%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Faccount.flags%26v%3Dc1721fefb9cebd72e7ff228bf7bad87911c5c8b17c32cc022980dc744bb3eb1f&validated=true')
        # 输入账号密码
        page.ele('.hwid-input userAccount').input('15012800919')
        page.ele('.hwid-input hwid-input-pwd').input('LEYOU123')

        # 点击登录按钮
        login_btn = page.ele('.normalBtn', timeout=10)
        login_btn.click()
        # 滑块验证重试逻辑
        for retry in range(3):
            print(f"尝试滑块验证 (第 {retry + 1} 次)...")
            success, headers = slide_test(page)
            if success:
                print("滑块验证成功")
                break
            else:
                print(f"滑块验证失败，等待1秒后重试...")
                sleep(1)
        else:
            print(f"滑块验证失败，已达最大重试次数 {3} 次")
        sleep(3)  # 等待登录完成

        # 初始化分页参数
        page_num = 1
        page_size = 100
        all_data = []
        has_more = True

        # # 分页查询循环
        while has_more:
            # 请求体数据
            payload = {
                "pageNum": page_num,
                "pageSize": page_size,
                "orderBy": "",
                "orderType": "",
                "startTime": "2025-01-01",
                "endTime": "2025-06-15",
                "campaignType": None,
                "timeLine": "STAT_REPORTING_TIME",
                "promotionType": 2,
                "campaignIds": [],
                "adgroupNameOrId": "",
                "productAppId": "",
                "creativeSizeId": "",
                "filterNoStat": 0,
                "serviceProviderIds": [],
                "flowResourceList": None,
                "marketingGoalList": None,
                "status": None,
                "productTypeList": None,
                "priceTypeList": None,
                "ocpxStatus": None,
                "deepOptimizeType": None,
                "changeToOcpcStatus": None,
                "ocpcStrategy": None,
                "objectiveTypeList": None,
                "simpleMode": None
            }
            try:
                # 发送POST请求
                response = requests.post(
                    "https://svc-drcn.ads.huawei.com/ppsdspportal/v1/adgroups/query",
                    headers=headers,
                    json=payload
                )
                # 检查响应状态
                if response.status_code == 200:
                    data = response.json()
                    # 检查是否有数据
                    if 'data' in data and 'adgroupStatistics' in data['data']:
                        current_page_data = data['data']['adgroupStatistics']
                        all_data.extend(current_page_data)

                        # 检查是否还有更多数据
                        if len(current_page_data) < page_size:
                            has_more = False
                        else:
                            page_num += 1
                    else:
                        print("响应数据格式不符合预期")
                        has_more = False
                else:
                    print(f"请求失败，状态码: {response.status_code}")
                    print("响应内容:", response.text)
                    has_more = False
            except requests.exceptions.RequestException as e:
                print(f"请求发生异常: {e}")
                has_more = False
            except ValueError as e:
                print(f"JSON解析错误: {e}")
                has_more = False
            # 添加适当的延迟，避免请求过于频繁
            sleep(1)
        print(f"168账户总共获取到 {len(all_data)} 条广告组数据")
        return all_data

    finally:
        page.quit()  # 确保关闭浏览器


def slide_test(page: ChromiumPage) -> tuple:
    """
    执行滑块验证并检查是否成功获取有效请求头
    参数:
        page: ChromiumPage 实例
    返回:
        tuple: (bool, headers) 表示验证是否成功以及获取到的请求头
    """
    try:
        # 1. 获取滑块图片元素
        target_element = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/img[2]')
        bg_element = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/img[1]')
        if not target_element or not bg_element:
            print("未找到滑块图片元素")
            return False, None
        # 2. 获取图片URL
        target_src = target_element.attr('src')
        bg_src = bg_element.attr('src')

        # # 4. 获取滑块和背景图片
        slide = ddddocr.DdddOcr(det=False, ocr=False)
        background_bytes = requests.get(bg_src, timeout=10).content
        target_bytes = requests.get(target_src, timeout=10).content
        res = slide.slide_match(target_bytes, background_bytes)

        raw_distance = res['target'][0]
        # 2. 精确计算
        scale_factor = 260 / 320  # 显示宽度/原始宽度
        calibrated_distance = raw_distance * scale_factor
        # 3. 动态补偿（小图居中补偿）
        small_img_width = 49  # 小图显示宽度
        compensated_distance = calibrated_distance - (small_img_width / 2) + 26  # +3px经验值
        target_length = compensated_distance

        print(f"识别距离为：{res}")
        print(f"需要滑动的距离: {target_length}px")

        slide_btn = page.ele('xpath:/html/body/div[3]/div[2]/div/div/div[2]/div/div[2]/div[2]')

        if not slide_btn:
            print("未找到滑块按钮")
            return False, None
        (page.actions.move_to(slide_btn)
         .wait(0.2)
         .m_hold(slide_btn)
         .wait(0.3)
         .move(target_length, 0, 0.8)
         .m_release())
        print(f"滑动的距离为: {target_length}px")

        # 5. 等待验证完成
        time.sleep(10)  # 等待验证结果

        # 6. 检查最新请求头
        try:
            latest_request = page.listen.wait(timeout=10)
            headers = latest_request.request.extra_info.headers
            cookies = headers.get('Cookie', '') if headers else ''

            if cookies:
                print("成功获取到请求头，包含Cookie:", cookies[:50] + "...")  # 打印部分Cookie避免泄露
                return True, headers
            else:
                print("获取到请求头但不包含Cookie")
                return False, None

        except Exception as e:
            print(f"获取请求头失败: {str(e)}")
            return False, None

    except Exception as e:
        print(f"滑块验证过程中出错: {str(e)}")
        return False, None




# 使用示例
if __name__ == '__main__':
    get_huawei_campaign_page168();


